#include <reg51.h>
#include "delay.h"

#define LCD_DATA  P0

sbit LCD_RS = P2^6;
sbit LCD_RW = P2^5;
sbit LCD_EN = P2^7;
sbit BUSY_FLAG = P0^7;

void check_busy();
void write_command(unsigned char c);
void write_data(unsigned char d);





void check_busy()
{
	LCD_RS = 0;
	LCD_RW = 1;
	do 
	{
		LCD_EN = 0;
		LCD_EN = 1;
	} while(BUSY_FLAG);
	LCD_EN = 0;
}

void write_command(unsigned char c) 
{
	check_busy();
	LCD_RS = 0;
	LCD_RW = 0;
	LCD_EN = 0;
	LCD_DATA = c;
	LCD_EN = 1;
	delay(1000);
	LCD_EN = 0;
	delay(1000);
}

void write_data(unsigned char d) 
{
	check_busy();
	LCD_RS = 1;
	LCD_RW = 0;
	LCD_EN = 0;
	LCD_DATA = d;
	LCD_EN = 1;
	delay(1000);
	LCD_EN = 0;
	delay(1000);
}

void LCD_Init() 
{
	write_command(0x38);//set 8-bit model  2 line 5x7Pixel
	write_command(0x0C);//display on cursor off blink off
	write_command(0x01);//screen clear
}

void LCD_Display(char* pc, char line, char pos, char num) 
{
	write_command(0x80 | pos | (line>1 ? 0x40 : 0x00) );//set position
	do{
		write_data(*pc++); //send to display
		num--;
	}	while(*pc != '\0' && num > 0);
}

void LCD_Clear() 
{
	write_command(0x01);//screen clear	
}
